//
//  CTVChannelsNet.m
//  Channltv
//
//  Created by Bruno Keymolen on 03/09/07.
//  Copyright 2007 channl.tv All rights reserved.
//
// Syncronous download
// Always overwrite
// Data slot

#import "CTVHTTPDataDownload.h"
#import "CTVCache.h"
#import "CTVConfig.h"
#import <stdio.h>

@implementation CTVHTTPDataDownload

-(id)initWithURLString:(NSString*)urlstring andDataReply:(CTVDataDownloadReply*)dataReply{
	[super init];
	
	m_dataReply = dataReply;								
	m_url = [[NSString alloc] initWithString:urlstring];
	m_cachePath = [[NSString alloc] initWithString:[CTVCache getDataCachePathForURL:m_url]];
	m_connection = nil;
	m_data = [[NSMutableData alloc] init];
	
	return self;
}


-(void)dealloc{
	if(m_connection){
		[m_connection cancel];
		[m_connection release];
	}			
	[m_data release];
	[m_url release];
	[m_cachePath release];
	[super dealloc];
}



-(NSString*)urlString{
	return m_url;
}


-(NSString*)cachePath{
	return m_cachePath;
}


//Return 0: caching url
//      -1: error
-(int)cache{
	
	
	//Async download
	NSURL* nurl = [NSURL URLWithString:m_url];
	NSMutableURLRequest* urlRequest=[NSMutableURLRequest requestWithURL:nurl
							cachePolicy:NSURLRequestReloadIgnoringCacheData
							timeoutInterval:15.0];


	//Modify some Headers
	[urlRequest setValue:[[CTVConfig GetInstance] userAgent] forHTTPHeaderField:@"User-Agent"];

	//Get the data
	m_connection=[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];

	if (m_connection == nil) {
		m_httpStatusCode = -901;
		return -1;
	}	
	
	//The download is ongoing
	return 0;
}





/*
 *
 * NSURLConnection Delegates
 *
 */
- (void)connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
}


- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
}



/* FAIL */
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
	NSLog(@"Error; RESOURCE download: %@ , cache entry: %@", m_url, m_cachePath);

	if(m_httpStatusCode == 0){
		m_httpStatusCode = -900;
	}

	NSString* sysString = [NSString stringWithFormat:@"rm %@", m_cachePath];
	NSLog(sysString);	
	system([sysString UTF8String]);
	
	//Done
	[m_dataReply finishDataDownload:self];
	[m_dataReply releaseDataDownload:self];

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
		
	//Write data to memory
	[m_data appendBytes:[data bytes] length:[data length]];
		
}



// Full header is available
// In rare cases, for example in the case of an HTTP load where the content type of the load data is 
// multipart/x-mixed-replace, the delegate will receive more than one connection:didReceiveResponse: message. 
// In the event this occurs, delegates should discard all data previously delivered by 
// connection:didReceiveData:, and should be prepared to handle the, potentially different,
// MIME type reported by the newly reported URL response.
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
	NSHTTPURLResponse* urlResponse = (NSHTTPURLResponse*)response;
	
	NSLog(@"Full header is received");

	m_httpStatusCode = [urlResponse statusCode];

	if([urlResponse statusCode] >= 400){
		//Could not download resource
		[m_connection cancel];
		[m_data setData:[NSData dataWithBytes:NULL length:0]];

		//Done
		[m_dataReply finishDataDownload:self];	
		[m_dataReply releaseDataDownload:self];
	}
}


-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse{
	//Return Value
	//The actual cached response to store in the cache. The delegate may return cachedResponse unmodified, 
	//return a modified cached response, or return nil if no cached response should be stored for the 
	//connection.
	return nil;
}


-(NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse{
	NSLog(@"Redirect while downloading %@", m_url);
	
	//Oops, we have a redirect, modify the headers to our needs
	NSMutableURLRequest* urlRequest= [request mutableCopyWithZone:nil];	
		
	//Modify some Headers
	[urlRequest setValue:[[CTVConfig GetInstance] userAgent] forHTTPHeaderField:@"User-Agent"];	
	
	return urlRequest;
}


-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
	
	if( [m_data length] > 0 ){
		[m_data writeToFile:m_cachePath atomically:YES];
	} 		
	
	//Done
	[m_dataReply finishDataDownload:self];	
	[m_dataReply releaseDataDownload:self];
}


-(int)httpStatusCode{
	return m_httpStatusCode;
}


@end
